﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class PlayerScript : MonoBehaviour
{

    public GameObject m_gCurStair,m_pStair;
    public Transform m_tParent;
    public bool m_bIsJump { get; set; }
    public bool m_bIsDead, m_bIsFinishJump;
    private Vector3 vDragBegin, vDragEnd;
    private bool m_bIsShow, m_bIsMoveCamera;
    private float m_fFloor, m_fFont, m_fVelX, m_fVelY, m_fMoveCameraDist, m_fMoveCameraTime;
    private int m_iJumpType;
    public UnityEngine.UI.Text m_tFloor, m_fFloor2;
    private Vector3  m_rotation, m_rotation2, m_vForward, m_vLeft,m_vTo,m_vFrom;

    // Use this for initialization
    void Start()
    {
        InitialListener();
        //增加事件触发
        EventDispatcher.btnEvent += onBtnEvent;
        EventDispatcher.dropEvent += onDropEvent;
        m_vForward = new Vector3(0, 1, 0);
        m_vLeft = new Vector3(1, 0, 0);
        m_bIsFinishJump = true;
    }

    // Update is called once per frame
    void Update()
    {
        /*
        if (m_bIsMoveCamera)
        {
            Camera.main.transform.Translate(0, m_fMoveCameraDist * Time.deltaTime, 0);
            m_fMoveCameraTime -= Time.deltaTime;
            if (m_fMoveCameraTime <= 0)
            {
                m_fMoveCameraTime = 0;
                m_bIsMoveCamera = false;
                Camera.main.transform.position = new Vector3(0f, 3.2f + m_gCurStair.transform.position.y, -10f);
            }
        }
        */
        if (GameData.gi.bIsGameRunning)
        {
            //检测周围是否有火球            
            Collider[] colliders = Physics.OverlapSphere(transform.position, 0.2f);
            if (colliders.Length > 0)
            {
                for (int i = 0; i < colliders.Length; i++)
                {
                    if (
                        (colliders[i].name == "FireBall_Notice" || colliders[i].name == "FireBall_Follow" || colliders[i].name == "Bird")
                        && GameData.pi.iPlayerStatus!=1)
                    {
                        m_fVelX = 0;
                        m_fVelY = 0;
                        m_bIsDead = true;
                        transform.GetComponent<SpriteRenderer>().color = Color.black;
                        NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_GameOver", null);
                    }
                }
            }
        }

        if (m_bIsJump)
        {
            transform.Translate(GameData.pi.fJumpV * Time.deltaTime * m_fVelX, 0, 0);
            transform.Translate(0, GameData.pi.fJumpV * Time.deltaTime * m_fVelY, 0);
            float g = 9.8f;
            if (m_iJumpType == 1)
            {
                m_fVelY = m_fVelY - g * Mathf.Sqrt(3 * g) * GameData.pi.fJumpV * Time.deltaTime * GameData.pi.fJumpDist;
                if (!m_bIsDead)
                {
                    if (m_fVelY <= -Mathf.Sqrt(g))
                    {
                        m_bIsJump = false;
                    }
                }
            }
            else if (m_iJumpType == 2)
            {
                m_fVelY = m_fVelY - g * Mathf.Sqrt(3 * g) * GameData.pi.fJumpV * Time.deltaTime * GameData.pi.fJumpDist;
                if (!m_bIsDead)
                {
                    if (m_fVelY <= -Mathf.Sqrt(3 * g))
                    {
                        m_bIsJump = false;
                    }
                }
            }
            else if (m_iJumpType == 3)
            {
                //原地上跳
                m_fVelY = m_fVelY - g * Mathf.Sqrt(2 * g) * GameData.pi.fJumpV * Time.deltaTime * GameData.pi.fJumpDist;
                if (m_fVelY <= -Mathf.Sqrt(2 * g))
                {
                    m_bIsJump = false;
                }
            }

            if (!m_bIsJump)
            {
                m_bIsFinishJump = true;
                if (m_iJumpType == 3)
                {
                    transform.position = m_vFrom;
                }
                else
                {
                    transform.position = m_vTo;
                }
                
                //transform.Translate(0, GameData.pi.fYAxisFix, GameData.pi.fZAxisFix);
            }
        }

    }

    private void InitialListener()
    {
        NotificationCenter.DefaultCenter().AddObserver(this, "PlayerScript_movePlayer");
        NotificationCenter.DefaultCenter().AddObserver(this, "PlayerScript_checkLife");
        NotificationCenter.DefaultCenter().AddObserver(this, "PlayerScript_ShowFloor");
    }


    private void Jump(Vector3 vFrom, Vector3 vTo, int iType, bool bIsDead = false)
    {
        //m_bIsJump = false;
        //transform.position = m_gCurStair.transform.position;
        //transform.Translate(0, GameData.pi.fYAxisFix, GameData.pi.fZAxisFix);
        m_bIsJump = true;
        m_bIsDead = bIsDead;
        float g = 9.8f;
        if (iType == 1)
        {
            //向非正上方跳
            //计算VX和VY
            float vX = 1 / (Mathf.Sqrt(3 / g) + Mathf.Sqrt(1 / g));
            float vY = Mathf.Sqrt(3 * g);
            if (vTo.y > vFrom.y)
            {
                //说明向左上 、 上 、 右上跳
                m_fVelY = vY;
                m_iJumpType = 1;
                if (vTo.x < vFrom.x)
                {
                    //说明向左上跳
                    m_fVelX = -vX;
                }
                else if (vTo.x == vFrom.x)
                {
                    //向正上跳
                    m_fVelX = 0;
                }
                else if (vTo.x > vFrom.x)
                {
                    //向右上跳
                    m_fVelX = vX;
                }
            }
            else
            {
                //说明向左下 、 下 、 右下跳
                vY = Mathf.Sqrt(g);
                m_fVelY = vY;
                m_iJumpType = 2;
                if (vTo.x < vFrom.x)
                {
                    //说明向左下跳
                    m_fVelX = -vX;
                }
                else if (vTo.x == vFrom.x)
                {
                    //向正下跳
                    m_fVelX = 0;
                }
                else if (vTo.x > vFrom.x)
                {
                    //向右下跳
                    m_fVelX = vX;
                }
            }
        }
        else if (iType == 2)
        {
            //向正上方跳
            //CommonFunctionA.logger("向上跳2222", 1);
            m_iJumpType = 3;
            m_fVelX = 0;
            m_fVelY = Mathf.Sqrt(2 * g);
        }
    }
    /*
    public void PlayerScript_ShowFloor(Notification n)
    {
        Hashtable adata = (Hashtable)n.data;
        m_fFloor = (float)adata["msg"];
        m_bIsShow = true;
        m_fFont = 20;
        m_tFloor.text = m_fFloor.ToString();
    }
     */

    public void onBtnEvent(GameObject btn, UserOperate.btnState btnState)
    {

    }

    public void onDropEvent(GameObject obj, UserOperate.dragState btnState, PointerEventData eventData)
    {

        if (GameData.gi.bIsGameRunning)
        {
            if (obj.name != "pnlDragCtrl")
            {
                return;
            }
            if (!m_bIsFinishJump)
            {
                return;
            }
            //CommonFunctionA.logger("111111111111", 1);
            
            if (btnState == UserOperate.dragState.dragStateBegin)
            {
                vDragBegin = eventData.position;
            }
            else if (btnState == UserOperate.dragState.dragStateDraging)
            {
                Transform tLine = transform.GetChild(0);
                Transform tLine2 = transform.GetChild(1);
                vDragEnd = eventData.position;
                //GameData.logger("-->"+(vDragEnd - vDragBegin), 1);
                //计算角度，如果在第一象限 -22.5~22.5度为正右，22.5~67.5为右上，67.5~115.5为正上；
                //20 - 27 左上 正上 右上 左 右 左下 正下 右下
                Vector3 targetDir = vDragEnd - vDragBegin;                
                float fAngle = Vector3.Angle(m_vLeft, targetDir);
                float fAngle2 = Vector3.Angle(m_vForward, targetDir);
                int iAction = MoveAction(fAngle, targetDir);
                Vector3 rotation = tLine.localEulerAngles;
                Vector3 rotation2 = tLine2.localEulerAngles;
                
                //如果在右侧，即用360 - fangle2 。 右侧条件为： vDragEnd.x - vDragBegin.x >0
                if (vDragEnd.x - vDragBegin.x > 0)
                {
                    rotation2.z = 360 - fAngle2;
                }
                else
                {
                    rotation2.z = fAngle2;
                }
                switch (iAction)
                {
                    //20 - 27 20左上 21正上 22右上 23左 24右 25左下 26正下 27右下
                    case 20:
                        rotation.z = 45;
                        break;
                    case 21:
                        rotation.z = 0;
                        break;
                    case 22:
                        rotation.z = 315;
                        break;
                    case 23:
                        rotation.z = 90;
                        break;
                    case 24:
                        rotation.z = 270;
                        break;
                    case 25:
                        rotation.z = 135;
                        break;
                    case 26:
                        rotation.z = 180;
                        break;
                    case 27:
                        rotation.z = 225;
                        break;
                }
                m_rotation = rotation;
                m_rotation2 = rotation2;
                StartCoroutine(ShowLine(0.1f, tLine, tLine2, 1));
            }
            else if (btnState == UserOperate.dragState.dragStateEnd)
            {
                //transform.GetChild(0).gameObject.SetActive(false);
                StartCoroutine(ShowLine(0.1f, transform.GetChild(0), transform.GetChild(1), 2));
                vDragEnd = eventData.position;
                //GameData.logger("-->"+(vDragEnd - vDragBegin), 1);
                //计算角度，如果在第一象限 -22.5~22.5度为正右，22.5~67.5为右上，67.5~115.5为正上；
                //20 - 27 左上 正上 右上 左 右 左下 正下 右下
                Vector3 targetDir = vDragEnd - vDragBegin;
                float fAngle = Vector3.Angle(m_vLeft, targetDir);
                m_bIsFinishJump = false;
                movePlayer(MoveAction(fAngle, targetDir));
            }
        }
    }

    private IEnumerator ShowLine(float time, Transform t, Transform t2, int iType)
    {
        yield return new WaitForSeconds(time);
        if (iType == 1)
        {
            t.localEulerAngles = m_rotation;
            t.gameObject.SetActive(true);
            t2.localEulerAngles = m_rotation2;
            t2.gameObject.SetActive(true);
        }
        else if (iType == 2)
        {
            t.gameObject.SetActive(false);
            t2.gameObject.SetActive(false);
        }
    }

    private int MoveAction(float fAngle, Vector3 targetDir)
    {
        int iAction = 0;
        if (targetDir.y >= 0)
        {
            //一二象限
            if (fAngle >= 0 && fAngle <= 22.5)
                iAction = 24;
            else if (fAngle >= 22.5 && fAngle <= 67.5)
                iAction = 22;
            else if (fAngle >= 67.5 && fAngle <= 115.5)
                iAction = 21;
            else if (fAngle >= 115.5 && fAngle <= 160.5)
                iAction = 20;
            else if (fAngle >= 160.5 && fAngle <= 180)
                iAction = 23;
        }
        else
        {
            //三四象限
            if (fAngle >= 0 && fAngle <= 22.5)
                iAction = 24;
            else if (fAngle >= 22.5 && fAngle <= 67.5)
                iAction = 27;
            else if (fAngle >= 67.5 && fAngle <= 115.5)
                iAction = 26;
            else if (fAngle >= 115.5 && fAngle <= 160.5)
                iAction = 25;
            else if (fAngle >= 160.5 && fAngle <= 180)
                iAction = 23;
        }
        return iAction;
    }

    public void PlayerScript_checkLife(Notification n)
    {
        //检测是否死亡
        Hashtable adata = (Hashtable)n.data;
        string name = adata["msg"].ToString();
        int iType = (int)adata["type"];
        if (name != null && m_gCurStair != null)
        {
            if (name.Equals(m_gCurStair.name))
            {
                if (GameData.pi.iPlayerStatus == 1 && iType == 3)
                {
                    return;
                    
                }                
                else
                {
                    if (iType == 3)
                    {
                        transform.GetComponent<SpriteRenderer>().color = Color.black;
                    }
                    gameObject.AddComponent<Rigidbody2D>();
                    m_bIsDead = true;
                    NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_GameOver", null);
                }
                               
            }
        }
    }

    private void movePlayer(int action)
    {
        int x = 0, y = 0;
        //20 - 27 左上 正上 右上 左 右 左下 正下 右下
        if (action >= 20 && action <= 22)
            y = 1;
        else if (action >= 23 && action <= 24)
            y = 0;
        else if (action >= 25 && action <= 27)
            y = -1;

        if (action == 20 || action == 23 || action == 25)
            x = -1;
        else if (action == 21 || action == 26)
            x = 0;
        else if (action == 22 || action == 24 || action == 27)
            x = 1;
        //GameData.logger("..." + transform.position.x, 1);
        //如果X超标，则修正
        float fX = m_gCurStair.transform.position.x + x * GameData.gi.fHorzValue;
        if (Mathf.Abs(fX) > GameData.gi.fHorzMaxBound)
        {
            fX = fX / Mathf.Abs(fX) * GameData.gi.fHorzMaxBound;
        }
        Vector3 v = new Vector3(fX,
            m_gCurStair.transform.position.y + y * GameData.gi.fVertValue,
            m_gCurStair.transform.position.z);
        //GameData.logger("当前楼梯坐标："+m_gCurStair.transform.position+" 判断坐标为：" + v + ",action:" + action,1);
        Collider[] colliders = Physics.OverlapSphere(v, 0.1f);
        bool bHasStair = false;
        GameObject gJumpStair = null;
        for (int k = 0; k < colliders.Length; k++)
        {
            if (colliders[k].name.Contains("stair_"))
            {
                gJumpStair = colliders[k].gameObject;
                bHasStair = true;
            }
        }
        Vector3 vFrom, vTo;
        vFrom = transform.position;
        m_vFrom = new Vector3(vFrom.x,vFrom.y,vFrom.z);
        m_vTo = vTo = new Vector3(v.x, v.y + GameData.pi.fYAxisFix, GameData.pi.fZAxisFix);
        if (!bHasStair)
        {
            
            if (GameData.pi.iPlayerStatus == 2)
            {
                //拥有飞行技能
                //需要在V位置创建一个隐形的普通梯子
                GameObject stair = Instantiate(m_pStair, v, Quaternion.identity) as GameObject;
                stair.name = "stair_hide";
                stair.transform.parent = m_tParent;
                stair.GetComponent<StairProperty>().m_bIsLive = true;
                m_gCurStair = stair;
                stair.SetActive(false);
                Jump(vFrom, vTo, 1);
                CommonFunctionA.MoveObjectTamplate(Camera.main.gameObject, Camera.main.transform.position,
                   new Vector3(m_gCurStair.transform.position.x, Camera.main.transform.position.y + y, Camera.main.transform.position.z),
                   1, 0.2f);

                string s = m_gCurStair.transform.position.y.ToString();
                if (GameData.gi.bIsGameMode)
                {
                    Hashtable adata2 = new Hashtable();
                    adata2["dirction"] = y;
                    NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_FixBackGround", adata2);
                    m_fFloor2.text = s;
                }
            }
            else
            {
                //正上跳不算输
                if (action == 21)
                {
                    CommonFunctionA.PlayJumpAudio(m_gCurStair, gameObject);
                    //CommonFunctionA.logger("向上跳了", 1);
                    Jump(vFrom, vTo, 2);
                }
                else
                {
                    //失败
                    //GameData.logger("失败", 1);
                    //tArrow.GetComponent<SpriteRenderer>().color = Color.red;
                    Jump(vFrom, vTo, 1, true);
                    NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_GameOver", null);
                }
            }
        }
        else
        {
            //在前一个上面显示箭头
            //移动上去
            Jump(vFrom, vTo, 1);
            m_gCurStair = gJumpStair.gameObject;
            StairProperty sp = m_gCurStair.GetComponent<StairProperty>();
            if (sp == null)
            {
                CommonFunctionA.logger("没有找到stair的组件<StairProperty>", 2);
                return;
            }
            //如果当前楼梯未激活，也是失败的
            if (sp.m_bIsLive == false && GameData.pi.iPlayerStatus!=1)
            {
                CommonFunctionA.logger("dead", 1);
                if (sp.m_iType == 3 )
                {
                    transform.GetComponent<SpriteRenderer>().color = Color.black;
                }
                m_bIsDead = true;
                NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_GameOver", null);
            }
            else
            {
                //播放对应的声音
                if (GameData.pi.iPlayerStatus == 2)
                {

                }
                else
                {
                    CommonFunctionA.PlayJumpAudio(m_gCurStair, gameObject);
                }
            }

            //如果是问题走对了，那么把颜色加绿
            if (sp.m_iType == 5)
            {
                //获取其父下的所有问题块
                Transform tQuestion = m_gCurStair.transform.parent;
                for (int i = 0; i < tQuestion.childCount; i++)
                {
                    if (tQuestion.GetChild(i).name.Contains("stair"))
                    {
                        tQuestion.GetChild(i).GetChild(0).GetChild(1).gameObject.SetActive(false);
                    }
                    Transform tChild = tQuestion.GetChild(i);
                    if (tChild.name.Contains("stair"))
                    {
                        if (!tChild.GetComponent<StairProperty>().m_bIsLive)
                        {
                            tQuestion.GetChild(i).GetChild(1).gameObject.SetActive(true);
                            Texture2D t2d = (Texture2D)CommonFunctionA.loadPicture("jc");
                            tQuestion.GetChild(i).GetChild(1).GetComponent<SpriteRenderer>().sprite = 
                                Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), new Vector2(0.5f, 0.5f));
                        }
                    }
                }

            }
            CommonFunctionA.MoveObjectTamplate(Camera.main.gameObject, Camera.main.transform.position,
            new Vector3(m_gCurStair.transform.position.x, Camera.main.transform.position.y + y, Camera.main.transform.position.z),
            1, 0.2f);

            string s = m_gCurStair.transform.position.y.ToString();
            if (GameData.gi.bIsGameMode)
            {
                Hashtable adata2 = new Hashtable();
                adata2["dirction"] = y;
                NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_FixBackGround", adata2);
                m_fFloor2.text = s;
            }
            sp.enableEffect();

            //如果吃到能量，加能量 
            if (sp.m_bIsEnegy)
            {
                //吃到能量，将能量条+1 ，移除能量，发出声音
                GameData.pi.iEnegyNum = GameData.pi.iEnegyNum + sp.m_iEnegy;
                Hashtable adata = new Hashtable();
                if (GameData.pi.iEnegyNum > GameData.gi.iEnegyNumMax)
                {
                    GameData.pi.iEnegyNum = GameData.gi.iEnegyNumMax;
                }
                //调用GameMain_Refresh刷新数据，以及显示技能按钮                
                NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_RefreshInterface", null);
                sp.m_bIsEnegy = false;
                m_gCurStair.transform.GetChild(3).gameObject.SetActive(false);
                CommonFunctionA.PlayAudio(gameObject, "enegyAbsorb");                
            }

            //移到终点，清除下方所有，并在最上面位置生成一个新的。重新跑
            if (m_gCurStair.transform.position.y % GameData.gi.iStairNumPassed == 0 && m_gCurStair.transform.position.y != GameData.gi.iTurnStartFloor && m_gCurStair.transform.position.y != 0)
            {
                
                Vector3 vEnd = new Vector3(m_gCurStair.transform.position.x, m_gCurStair.transform.position.y, GameData.gi.fZAxisStair);
                Hashtable adata1 = new Hashtable();
                adata1["msg"] = vEnd;
                NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_BeginGeneraling", adata1);
            }
        }
    }

    /*
    private void MoveCamera(Vector3 v, float fTime)
    {
        m_fMoveCameraDist = v.y / fTime;
        m_fMoveCameraTime = fTime;
        m_bIsMoveCamera = true;
    }
    */

    public void PlayerScript_movePlayer(Notification n)
    {
        Hashtable adata = (Hashtable)n.data;
        int action = (int)adata["msg"];
        movePlayer(action);
    }
}
